
package com.kq.xtoolkit;

import android.animation.Animator;
import android.animation.Animator.AnimatorListener;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceFragment;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.ads.AdRequest;
import com.google.ads.AdView;
import com.kq.xtoolkit.utils.XUtils;

public class XToolKitSettings extends Activity implements OnSharedPreferenceChangeListener,
        OnClickListener {
    public static final String PREFS_NAME = "xtoolkit_settings";

    private SharedPreferences mySharedPreference;

    /**
     * Default is true.
     */
    public static final String ENABLE_SWITCH = "switch_preference";

    public static final String PREF_CUSTOM_SIGNAL = "lamp_check_preference";

    private LinearLayout lampArea;

    private TextView lampText;

    private Button sosButton;

    private Button sendButton;

    private static final long BASE_INTERVAL = 100;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.settings);
        lampArea = (LinearLayout)findViewById(R.id.lamp_area);
        lampText = (TextView)findViewById(R.id.lamp_text);
        sosButton = (Button)findViewById(R.id.sos_button);
        sendButton = (Button)findViewById(R.id.send_button);
        sosButton.setOnClickListener(this);
        sendButton.setOnClickListener(this);

        mySharedPreference = getSharedPreferences(PREFS_NAME, 0);
        mySharedPreference.registerOnSharedPreferenceChangeListener(this);
        // create preference view
        createPreferenceView();
        // create ad
        createAdView();
        // get sharedPreference values and make initialize
        boolean enable = getBooleanPreference(ENABLE_SWITCH);
        if (enable) {
            startService(new Intent(this, XToolKitService.class));
        }
    }

    @Override
    protected void onStart() {
        super.onStart();
        boolean lampEnable = getBooleanPreference(PREF_CUSTOM_SIGNAL);
        if (lampEnable) {
            lampArea.setVisibility(View.VISIBLE);
        } else {
            lampArea.setVisibility(View.GONE);
        }
    }

    @Override
    protected void onDestroy() {
        if (mySharedPreference != null) {
            mySharedPreference.unregisterOnSharedPreferenceChangeListener(this);
        }
        super.onDestroy();
    }

    private void createPreferenceView() {
        // Display the fragment as the main content.
        getFragmentManager().beginTransaction().replace(R.id.content, new PrefsFragment()).commit();

    }

    private void createAdView() {
     // Look up the AdView as a resource and load a request.
        AdView adView = (AdView)this.findViewById(R.id.adView);
        adView.loadAd(new AdRequest());
    }

    public static class PrefsFragment extends PreferenceFragment {
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            // first create shared preference
            getPreferenceManager().setSharedPreferencesName(PREFS_NAME);
            // Load the preferences from an XML resource
            addPreferencesFromResource(R.xml.setting_preferences);
        }
    }

    @Override
    public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
        final boolean value = sharedPreferences.getBoolean(key, true);
        if (key.equals(ENABLE_SWITCH)) {
            if (value) {
                startService(new Intent(this, XToolKitService.class));
            } else {
                stopService(new Intent(this, XToolKitService.class));
            }
        } else if (key.equals(PREF_CUSTOM_SIGNAL)) {
            if (value) {
                lampArea.setVisibility(View.VISIBLE);
            } else {
                lampText.setText("");
                lampArea.setVisibility(View.GONE);
            }
        } else {
            XUtils.LogD("Exception: not find specified preference.");
        }
    }

    private boolean getBooleanPreference(String key) {
        if (mySharedPreference == null) {
            mySharedPreference = getSharedPreferences(PREFS_NAME, 0);
        }
        boolean value = mySharedPreference.getBoolean(key, false);
        return value;
    }

    @Override
    public void onClick(View v) {
        final int viewId = v.getId();
        switch (viewId) {
            case R.id.sos_button:
                lampText.setText("SOS");
                break;
            case R.id.send_button:
                CharSequence text = lampText.getText();
                if (!TextUtils.isEmpty(text) && isMessageValidate(text)) {
                    new LampTask().execute(text);
                }
                break;
        }
    }

    private boolean isMessageValidate(CharSequence text) {
        for (int i = 0; i < text.length(); i++) {
            char c = text.charAt(i);
            if (Character.isWhitespace(c)) {
                continue;
            }
            if (c >= 'A' && c <= 'Z') {
                continue;
            } else if (c >= 'a' && c <= 'z') {
                continue;
            } else if (c >= '0' && c <= '9') {
                continue;
            } else {
                Toast.makeText(this, R.string.invalid_text_prompt, Toast.LENGTH_SHORT).show();
                return false;
            }
        }
        return true;
    }

    private class LampTask extends AsyncTask<CharSequence, Void, Void> {

        private boolean mFliper;

        @Override
        protected Void doInBackground(CharSequence... params) {
            CharSequence text = params[0];
            XUtils.decodeLampMessage(text.toString());
            mFliper = false;
            try {
                // give some time to UI thread finish the last animation
                wait(500);
            } catch (Exception e) {
                // TODO: handle exception
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            sendButton.setEnabled(true);
            sosButton.setEnabled(true);
            // make sure mFliper is false
            mFliper = false;
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            sosButton.setEnabled(false);
            sendButton.setEnabled(false);
            mFliper = true;
            startFlipAnim();
        }

        private void startFlipAnim() {
            lampText.animate().rotationYBy(-360).setDuration(300)
                    .setListener(new AnimatorListener() {

                        @Override
                        public void onAnimationStart(Animator animation) {
                            // TODO Auto-generated method stub

                        }

                        @Override
                        public void onAnimationRepeat(Animator animation) {
                            // TODO Auto-generated method stub

                        }

                        @Override
                        public void onAnimationEnd(Animator animation) {
                            // mFliper controls whether we repeat the animation
                            if (mFliper)
                                startFlipAnim();
                        }

                        @Override
                        public void onAnimationCancel(Animator animation) {
                            // TODO Auto-generated method stub

                        }
                    }).start();
            lampText.postInvalidate();
        }
    }

}
